//
//  Registration.m
//  NZTaxi
//
//  Created by Allan Vergara on 29/09/10.
//  Copyright 2010 List-it. All rights reserved.
//

#import "Registration.h"
#import "TextFieldTVC.h"
#import "MyManager.h"
#import "JSON/JSON.h"

@interface Registration(Private)
-(void)showRegisterButton;
-(void)hideActivityIndicator;
-(void)showActivityIndicator;
-(void)handleError:(NSError *)error;
@end

@implementation Registration

@synthesize responseData, nameCell, numberCell;

#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];    
	    	
	self.navigationItem.title = @"Register";
	[self showRegisterButton];
}

-(IBAction)btnRegisterClick:(id)sender {
	
    if ([nameCell.TextField.text length] > 0 && [numberCell.TextField.text length] > 0) {
        MyManager *sharedManager = [MyManager sharedMyManager];
        
        /*if ([numberCell.TextField.text isEqualToString:sharedManager.customerMobileNo]) {
            NSDictionary *userInfoAlreadyExist = [NSDictionary dictionaryWithObject:@"The mobile number is already registered. Enter a different mobile number and try again."
                                                                             forKey:NSLocalizedDescriptionKey];
            NSError *errorAlreadyExist = [NSError errorWithDomain:@"HTTP" code:0 userInfo:userInfoAlreadyExist];
            [self handleError:errorAlreadyExist];
        } else {*/
            sharedManager.customerMobileNo = numberCell.TextField.text;
            sharedManager.customerName = nameCell.TextField.text;
            NSString *registerURL = [[NSString alloc] initWithFormat:@"%@%@%@?deviceID=%@&mobileNo=%@&customerName=%@", 
                                     sharedManager.listItDomain, 
                                     sharedManager.webServicePath,
                                     sharedManager.registerCustomerDeviceAPI,
                                     sharedManager.deviceUDID,
                                     sharedManager.customerMobileNo,
                                     sharedManager.customerName];

            NSURL *url = [NSURL URLWithString:[registerURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            [self showActivityIndicator];
            
            [registerURL release];
            [request release];
            [connection release];
        //}
    } else {        
		NSDictionary *userInfoEmptyFields = [NSDictionary dictionaryWithObject:@"Enter your name and mobile number. Please try again."
                                                             forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"HTTP" 
											 code:0 
										 userInfo:userInfoEmptyFields];
		[self handleError:error];
    }
}

#pragma mark -
#pragma mark Messaging delegate
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
	UIAlertView *alert;
	switch (result) {
		case MessageComposeResultCancelled:
			NSLog(@"Cancelled");
			break;
		case MessageComposeResultFailed:
			alert = [[UIAlertView alloc] initWithTitle:@"MyApp" message:@"Unknown Error"
														   delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
			[alert show];
			[alert release];
			break;
		case MessageComposeResultSent:
			
			break;
		default:
			break;
	}
	
	[self dismissModalViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    
    return 3;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {        
    static NSString *CellIdentifier = @"Cell";    
    TextFieldTVC *cell = (TextFieldTVC *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	MyManager *sharedManager = [MyManager sharedMyManager];
	
    if (cell == nil) {
		NSString *nibName = @"TextFieldTVC";
		NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
		cell = [topLevelObjects objectAtIndex:0];
    }
    	
    if (indexPath.section == 0) {
        switch(indexPath.row) {
			case 0:
				if (sharedManager.isCustomerRegistered == NO) {
					cell.Caption.text = @"Welcome Guest!";					
				} else {					
					cell.Caption.text = [[NSString alloc] initWithFormat:@"Welcome %@!", sharedManager.customerName];
				}
				[cell.TextField removeFromSuperview];
				break;
            case 1:
                cell.Caption.text = @"Name:";
				if (sharedManager.isCustomerRegistered == YES) {
					cell.TextField.text = sharedManager.customerName;
				}
                nameCell = cell;
                break;
            case 2:
                cell.Caption.text = @"Mobile No:";
                [cell.TextField setKeyboardType:UIKeyboardTypeNumberPad];
				if (sharedManager.isCustomerRegistered == YES) {
					cell.TextField.text = sharedManager.customerMobileNo;
				}
                numberCell = cell;
                break;
        }
    }    	
    
    return cell;
}

/*
 *	Expected JSON reply format : 
 *		{ "d" : { "RequestJob" : { "status":200, "message":"OK" } } }
 *
 *	TODO: check for empty status
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	// alloc new string for JSon load
	NSString *jsonStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	// assign the new string to a static string so we can release jsonString
	NSString *cleanStr = [jsonStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
	cleanStr = [cleanStr stringByReplacingOccurrencesOfString:@"\"{" withString:@"{"];
	cleanStr = [cleanStr stringByReplacingOccurrencesOfString:@"}\"" withString:@"}"];
	
	NSDictionary *dictionary = [cleanStr JSONValue];
	NSDictionary *cleanDictionary = (NSDictionary *)[dictionary objectForKey:@"d"];
	
	NSDictionary *result = (NSDictionary *)[cleanDictionary objectForKey:@"RegisterCustomerDevice"];
	
	NSInteger status = [[result objectForKey:@"status"] integerValue];
	
	NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
	MyManager *sharedManager = [MyManager sharedMyManager];
	
	switch (status) {
		case 500:
			// TODO: issue error message
			break;
		case 200:
			[preferences setObject:nameCell.TextField.text forKey:@"accnt-customer-name"];
			[preferences setObject:numberCell.TextField.text forKey:@"accnt-mobileno"];
			
			// persist data to disk
			[preferences synchronize];
			
			// update global variable
			sharedManager.customerName = nameCell.TextField.text;
			sharedManager.customerMobileNo = numberCell.TextField.text;
			sharedManager.isCustomerRegistered = YES;
			
			// reload table view to reflect the update ( e.g. welcome message )
			[self.tableView reloadData];
			break;
		default:			
			break;
	}
	
	[self hideActivityIndicator];
	[self showRegisterButton];
	[responseData release];
	responseData = nil;
}

#pragma mark -
#pragma mark Button

-(void)showRegisterButton {
	UIBarButtonItem *registerButton = [[UIBarButtonItem alloc] init];
	
	registerButton.title = @"Register";
	registerButton.target = self;
	registerButton.action = @selector(btnRegisterClick:);	
	self.navigationItem.rightBarButtonItem = registerButton;
	
	[registerButton release];	
}

#pragma mark -
#pragma mark Activity Indicator
-(void)showActivityIndicator {
	UIActivityIndicatorView *activityIndicatorRightBarItem = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
	[activityIndicatorRightBarItem startAnimating];
	UIBarButtonItem *activityItem = [[UIBarButtonItem alloc] initWithCustomView:activityIndicatorRightBarItem];
	[activityIndicatorRightBarItem release];
	self.navigationItem.rightBarButtonItem = activityItem;	
}

-(void)hideActivityIndicator {
	self.navigationItem.rightBarButtonItem = nil;
}

#pragma mark -
#pragma mark Error/Message Handler

- (void)handleError:(NSError *)error {
	NSString *errorMessage = [error localizedDescription];
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" 
														message:errorMessage 
													   delegate:nil 
											  cancelButtonTitle:@"OK" otherButtonTitles:nil];
	
	[alertView show];
	[alertView release];
}

#pragma mark -
#pragma mark Sockets

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    if (responseData == nil) {
		responseData = [[NSMutableData alloc] init];
	}
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {	    
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    
    // http code within 200 range is ok
    if ((([httpResponse statusCode]/100) == 2)) {
        [responseData setLength:0];
    } else {
        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"Problem encountered while connecting to the server. Please try again."
                                                             forKey:NSLocalizedDescriptionKey];
        NSError *error = [NSError errorWithDomain:@"HTTP" 
											 code:[httpResponse statusCode] 
										 userInfo:userInfo];
		[self hideActivityIndicator];
		[self showRegisterButton];
        [self handleError:error];
    }		
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	if ([error code] == kCFURLErrorNotConnectedToInternet){
		NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"You have a problem with your internet connection. Please try again." 
															 forKey:NSLocalizedDescriptionKey ];
		
        NSError *noConnectionError = [NSError errorWithDomain:@"HTTP"
                                                         code:kCFURLErrorNotConnectedToInternet
                                                     userInfo:userInfo];
		[self handleError:noConnectionError];
	} else {
		[self handleError:error];
	}
	
	[self hideActivityIndicator];
	[self showRegisterButton];
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.row == 0) {
		return 40;
	}
    return 80;
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}

- (void)dealloc {
    [super dealloc];
}

@end
